package StartUp;

import RDFManager.FileReader;
import RDFManager.JenaReader;
import RDFManager.RDFOutput;
import org.apache.jena.rdf.model.Model;
import org.apache.jena.rdf.model.ModelFactory;
import org.apache.jena.riot.RDFDataMgr;

import java.io.File;
import java.util.Objects;

public class FormatConverter {
  private static void ttl2nt(String inputFileName, String outputFileName) {
    Model model = JenaReader.turtle(inputFileName);
    RDFOutput.out_nTriples(model, outputFileName);
    System.out.println("Convert Successfully");
  }

  private static void nt2ttl(String inputFileName, String outputFileName) {
    Model model = JenaReader.ntriples(inputFileName);
    RDFOutput.out_turtle(model, outputFileName);
    System.out.println("Convert Successfully");
  }

  private static void rdf2nt(String inputFileName, String outputFileName) {
    Model model = JenaReader.rdfxml(inputFileName);
    RDFOutput.out_nTriples(model, outputFileName);
    System.out.println("Convert Successfully");
  }

  private static void rdf2ttl(String inputFileName, String outputFileName) {
    Model model = JenaReader.rdfxml(inputFileName);
    RDFOutput.out_turtle(model, outputFileName);
    System.out.println("Convert Successfully");
  }

  private static void changeToTTL(File inputFile) {
    Model model = ModelFactory.createDefaultModel();
    RDFDataMgr.read(model, inputFile.getAbsolutePath());
    String extension = fileExtensionChecker(inputFile);
    if (extension != null) {
      if (extension.equals("nt")) {
        RDFOutput.out_turtle(model, inputFile.getName().replace("_ntriples.nt", "_ttl.ttl"));
      } else if (extension.equals("rdf")){
        RDFOutput.out_turtle(model, inputFile.getName().replace("_rdf.rdf","_ttl.ttl"));
      }
    }
  }

  private static void changeToNT(File inputFile) {
    Model model = ModelFactory.createDefaultModel();
    RDFDataMgr.read(model, inputFile.getAbsolutePath());
    String extension = fileExtensionChecker(inputFile);
    if (extension != null) {
      if (extension.equals("ttl")) {
        RDFOutput.out_nTriples(model, inputFile.getName().replace("_ttl.ttl", "_ntriples.nt"));
      } else if (extension.equals("rdf")) {
        RDFOutput.out_nTriples(model, inputFile.getName().replace("_rdf.rdf", "_ntriples.nt"));
      }
    }
  }


  private static String fileExtensionChecker(File inputFile) {
    String fileName = inputFile.getName();
    int lastDot = fileName.lastIndexOf('.');
    if (lastDot > 0 && lastDot < fileName.length() - 1) {
      return fileName.substring(lastDot + 1);
    } else {
      return null;
    }
  }

  public static void main(String[] args) {
    changeToNT(Objects.requireNonNull(FileReader.readFile()));
  }
}
